<template>
  <div class="card-wrap flex-column justify-end card-padding">
    <el-form :model="form" ref="contract" label-width="150px" :rules="rules" :label-position="type =='detail'?'right':'top'" :disabled="type=='detail'">
      <!-- 其他信息 -->
      <div class="card-title-wrap">
        <span>合同信息</span>
        <span></span>
      </div>
      <div :style="{marginLeft: (type == 'detail'?'':'50px')}">
        <div style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 70%;">
          <div style="min-width: 370px;">
            <el-form-item label="合同数目:" prop="supplementContract.quantityDelivery">
              <el-input maxlength="3" v-model="form.supplementContract.quantityDelivery" @change="handleInput"></el-input>
            </el-form-item>
          </div>
          <div style="min-width: 370px">
            <el-form-item label="双方数目:">
              <el-input v-model="bothSides" readonly></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 70%;">
          <div style="min-width: 370px;">
            <el-form-item label="合同预计开始日期:" prop="supplementContract.timeStart">
              <el-date-picker style="width: 100%;" @change="changeTime" value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-model="form.supplementContract.timeStart" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </div>
          <div style="min-width: 370px;">
            <el-form-item label="合同预计结束日期:" prop="supplementContract.timeFinish">
              <el-date-picker style="width: 100%;" readonly value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-model="form.supplementContract.timeFinish" type="date">
              </el-date-picker>
            </el-form-item>
          </div>
        </div>
        <!-- 新增需求----------------------------------------------------------------开始 -->
        <div v-if="(($route.query.rentType==1 || $route.query.rentType==3)) || ((form.rentType ==1 || form.rentType ==3))" style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 70%;">
          <div style="min-width: 370px;">
            <el-form-item label="新车交付前替车日租金(元/天/台):" prop="supplementContract.dailyRentBeforeDelivery">
              <el-input @input="form.supplementContract.dailyRentBeforeDelivery = form.supplementContract.dailyRentBeforeDelivery.replace(/[^\d/]/g, '')" style="width: 100%;" v-model="form.supplementContract.dailyRentBeforeDelivery"></el-input>
            </el-form-item>
          </div>
          <!-- @input="form.supplementContract.dailyRentBeforeDelivery = form.supplementContract.dailyRentBeforeDelivery.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" -->
          <div style="min-width: 370px;">
            <el-form-item label="替车是否计入合同期:" prop="supplementContract.tenancyCalcInclusiveReplacementKey">
              <el-radio-group v-model="form.supplementContract.tenancyCalcInclusiveReplacementKey">
                <el-radio :label="'2'">否</el-radio>
                <el-radio :label="'1'">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
        <div style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 71.5%;">
          <div style="min-width: 390px;">
            <el-form-item label="是否限制开票日:" prop="supplementContract.limitInvoicingDaysKey">
              <div style="display: flex;justify-content: start;align-items: center;min-height: 70px;">
                <el-radio-group v-model="form.supplementContract.limitInvoicingDaysKey">
                  <el-radio :label="'2'">否</el-radio>
                  <el-radio :label="'1'">是</el-radio>
                </el-radio-group>
                <div v-if="form.supplementContract.limitInvoicingDaysKey ==1" style="margin-left: 20px; display: flex;justify-content:start;align-items: center;">
                  <span> 每月的</span>
                  <span style="margin-top: 15px;">
                    <el-form-item label="" prop="supplementContract.billingDay">
                      <el-input-number style="margin-left:5px;margin-right: 5px;" v-model="form.supplementContract.billingDay" controls-position="right" :min="0" :max="999999999" />
                    </el-form-item>
                  </span>
                  <span>日</span>
                </div>
              </div>
            </el-form-item>
          </div>
          <div style="min-width: 390px;">
            <el-form-item label="是否限制租金支付日:" prop="supplementContract.restrictedPaymentDayKey">
              <div style="display: flex;justify-content: start;align-items: center;min-height: 70px;">
                <el-radio-group v-model="form.supplementContract.restrictedPaymentDayKey">
                  <el-radio :label="'2'">否</el-radio>
                  <el-radio :label="'1'">是</el-radio>
                </el-radio-group>
                <div v-if="form.supplementContract.restrictedPaymentDayKey ==1" style="margin-left: 20px; display: flex;justify-content:start;align-items: center;">
                  <span> 每月的</span>
                  <span style="margin-top: 15px;">
                    <el-form-item label="" prop="supplementContract.paymentDay">
                      <el-input-number style="margin-left:5px;margin-right: 5px;" v-model="form.supplementContract.paymentDay" controls-position="right" :min="0" :max="999999999" />
                    </el-form-item>
                  </span>
                  <span>日前支付租金</span>
                </div>
              </div>
            </el-form-item>
          </div>
        </div>
        <div style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 70%;margin-top: 30px;">
          <div style="min-width: 370px;">
            <el-form-item label="授权委托指定人:" prop="supplementContract.authorizedUser">
              <el-input style="width: 100%;" maxlength="30" v-model="form.supplementContract.authorizedUser"></el-input>
            </el-form-item>
          </div>
          <div style="min-width: 370px;">
            <el-form-item label="授权委托指定人身份证号:" prop="supplementContract.authorizedUserIdNo">
              <el-input style="width: 100%;" maxlength="18" v-model="form.supplementContract.authorizedUserIdNo"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 70%;">
          <div style="min-width: 370px;">
            <el-form-item label="合同是否体现租金支付表:" prop="supplementContract.includesRentPaymentScheduleKey">
              <el-radio-group v-model="form.supplementContract.includesRentPaymentScheduleKey">{{ form.supplementContract.includesRentPaymentScheduleKey }}
                <el-radio :label="'2'">否</el-radio>
                <el-radio :label="'1'">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div style="min-width: 370px;" v-if="form.supplementContract.includesRentPaymentScheduleKey ==1">
            <el-form-item label="租金支付表车牌号:" prop="supplementContract.paymentScheduleCarPlateNo">
              <el-input style="width: 100%;" v-model="form.supplementContract.paymentScheduleCarPlateNo"></el-input>
            </el-form-item>
          </div>
        </div>
        <div v-if="form.supplementContract.includesRentPaymentScheduleKey ==1" style="display: flex;justify-content:space-between;align-items: center;flex-wrap: wrap;width: 70%;">
          <div style="min-width: 370px;">
            <el-form-item label="租金支付表车架号:" prop="supplementContract.paymentScheduleCarVinNo">
              <el-input style="width: 100%;" v-model="form.supplementContract.paymentScheduleCarVinNo"></el-input>
            </el-form-item>
          </div>
          <div style="min-width: 370px;">
            <el-form-item label="租金支付表租金合计:" prop="supplementContract.paymentScheduleTotalRent">
              <p style="width: 100%; background-color: #f5f7fa;border-radius: 4px;box-sizing: border-box;padding-left: 10px;border: 1px solid #DCDFE6;">{{ format_thousand(totalPrice) }}</p>
            </el-form-item>
          </div>
        </div>
        <el-table :data="form.supplementContract.paymentScheduleList" v-if="form.supplementContract.includesRentPaymentScheduleKey ==1">
          <el-table-column label="租金期数" align="center">
            <template #default="{ row, $index }">
              <el-form-item :prop="'supplementContract.'+'paymentScheduleList.' + $index + '.periods'" :rules="{ required: true, trigger: 'blur', message: '请输入租金期数' }" placeholder="请输入内容">
                <el-input maxlength="30" style="width: 100%" clearable v-model="row.periods"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="支付日期" align="center">
            <template #default="{ row, $index }">
              <el-form-item :prop="'supplementContract.'+'paymentScheduleList.' + $index + '.paymentDate'" :rules="{ required: true, trigger: 'blur', message: '请选择支付日期' }" v-model="row.paymentDate" placeholder="请输入内容">
                <el-date-picker style="width: 100%" value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-model="row.paymentDate" type="date" placeholder="选择日期" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="月租金(RMB,含税)" align="center">
            <template #default="{ row, $index }">
              <el-form-item :prop="'supplementContract.'+'paymentScheduleList.' + $index + '.rent'" :rules="{ required: true, trigger: 'blur', message: '请输入月租金(RMB,含税)' }" v-model="row.paymentDate" placeholder="请输入内容">
                <el-input clearable v-model="row.rent" @input="row.rent = row.rent.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')" maxlength="30" placeholder="请输入内容" style="width: 100%"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="80">
            <template slot-scope="scope">
              <el-form-item>
                <el-button type="text" @click="deleGr(scope)">删除</el-button>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: center" v-if="form.supplementContract.includesRentPaymentScheduleKey ==1">
          <el-button type="text" size="mini" icon="el-icon-plus" @click="addExtension">添加租期</el-button>
        </div>

        <!-- 新增需求----------------------------------------------------------------结束 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="其他合同附件上传:">
              <ImageCommon :up-type="1" info="选择附件" :limit="8" :disabled="type =='detail'" v-model="form.supplementContract.accessory"></ImageCommon>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input v-model="form.remark" :autosize="{ minRows: 8, maxRows: 20}" type="textarea" maxlength="500"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>
  <script>
export default {
  name: "contract",
  dicts: ["ven_dee"],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },
  computed: {
    form: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            that.$emit("input", { ...target, [key]: value });
            return true;
          },
        });
        return proxy;
      },
    },
    totalPrice() {
      if (this.value.supplementContract.paymentScheduleList.length > 0) {
        return this.value.supplementContract?.paymentScheduleList?.reduce(function (prev, curr) {
          return Number(prev) + Number(curr.rent);
        }, 0);
      } else {
        return 0;
      }
    },
    bothSides() {
      return Number(
        this.form.supplementContract.quantityDelivery == null
          ? 0
          : this.form.supplementContract.quantityDelivery
      ) /
        2 ==
        0
        ? null
        : Number(
          this.form.supplementContract.quantityDelivery == null
            ? 0
            : this.form.supplementContract.quantityDelivery
        ) / 2;
    },
    type() {
      let status;
      switch (this.state) {
        case "write":
          status = "edit";
          break;
        case "disabled":
          status = "detail";
          break;
        case "readonly":
          status = "detail";
          break;
        case "detail":
          status = "detail";
          break;
        case "edit":
          status = "edit";
        case "add":
          status = "add";
          break;
      }
      return status;
    },
  },
  data() {
    var checkIdCard = (rule, value, callback) => {
      const idCardReg = /^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|[Xx])$/;
      if (!value) {
        return callback(); // 如果不填写则不进行验证
      }
      if (!idCardReg.test(value)) {
        callback(new Error('身份证号格式不正确'));
      } else {
        callback();
      }
    };
    return {
      pattern: /^[2-9]\d*$/,
      rules: {
        supplementContract: {
          authorizedUserIdNo: [
            { validator: checkIdCard, trigger: 'blur' }
          ],
          billingDay: [
            {
              required: true,
              message: "请输入限制开票日",
              trigger: "blur",
            },
          ],
          paymentDay: [
            {
              required: true,
              message: "请输入租金支付日",
              trigger: "blur",
            },
          ],
          Number: [
            {
              required: true,
              message: "请输入新车交付前替车日租金",
              trigger: "blur",
            },
          ],
          tenancyCalcInclusiveReplacementKey: [
            {
              required: true,
              message: "请选择替车是否计入合同期",
              trigger: "change",
            },
          ],
          dailyRentBeforeDelivery: [
            {
              required: true,
              message: "请输入新车交付前替车日租金",
              trigger: "change",
            },
          ],
          quantityDelivery: [
            {
              required: true,
              message: "请输入合同数目(偶数)",
              trigger: "blur",
            },
          ],
          timeStart: [
            {
              required: true,
              message: "请选择开始时间",
              trigger: "change",
            },
          ],
          timeFinish: [
            {
              required: true,
              message: "请添加结束时间",
              trigger: "change",
            },
          ],
        },
        // contractTime: [
        //   {
        //     type: 'array',
        //     required: true,
        //     message: '请选择合同时间',
        //     fields: {
        //       0: { type: 'string', required: true, message: '请选择开始日期' },
        //       1: { type: 'string', required: true, message: '请选择结束日期' },
        //     },
        //   },
        // ],
      },
    };
  },
  created() {
    // if (this.form.orderStatus && this.form.orderStatus !== '1') {
    //   this.form.contractTime = [this.form.supplementContract.timeStart, this.form.supplementContract.timeFinish]
    // }
  },
  methods: {
    addExtension() {
      this.form.supplementContract.paymentScheduleList.push({ rent: null })
    },
    deleGr(row) {
      this.form.supplementContract.paymentScheduleList.splice(row.$index, 1)
    },
    addOneMonth(dateString, month) {
      const date = new Date(dateString);
      date.setMonth(date.getMonth() + Number(month));
      date.setDate(date.getDate() - 1)
      return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式的日期字符串
    },
    changeTime() {
      console.log(this.form.supplementContract.timeStart);
      if (this.form.supplementContract.timeStart == null) {
        this.$set(this.form.supplementContract, 'timeFinish', null)
      } else {
        let end = this.addOneMonth(this.form.supplementContract.timeStart, Number(localStorage.getItem('planTenancyTypeStr')))
        this.$set(this.form.supplementContract, 'timeFinish', end)
      }
    },
    validateInput() {
      const regex = /^[1-9]*[02468]$/;
      if (!regex.test(this.form.supplementContract.quantityDelivery)) {
        this.form.supplementContract.quantityDelivery =
          this.form.supplementContract.quantityDelivery.slice(0, -1);
      }
    },
    handleInput(value) {
      console.log(value);
      this.form.supplementContract.quantityDelivery = this.form.supplementContract.quantityDelivery.replace(/\D/g, '');
      if (Number(value) % 2 !== 0) {
        this.form.supplementContract.quantityDelivery = "";
      }
    },
    valid() {
      return new Promise(async (resolve) => {
        let result = true;
        let refs = Object.values(this.$refs);
        for (let index = 0; index < refs?.length; index++) {
          const ref = refs[index];
          if (Object.prototype.toString.call(ref) == "[object Array]") {
            for (let i = 0; i < ref.length; i++) {
              const element = ref[i];
              if (element?.valid) {
                let rc = await element?.valid?.();
                result = result && rc;
              }
              if (element?.validate) {
                let rf = await this._valid(ref);
                result = result && rf;
              }
              if (element?.form_validate) {
                let rf = await this._valid(ref, "form_validate");
                result = result && rf;
              }
            }
          } else {
            if (ref?.valid) {
              let rc = await ref?.valid?.();
              result = result && rc;
            }
            if (ref?.validate) {
              let rf = await this._valid(ref);
              result = result && rf;
            }
            if (ref?.form_validate) {
              let rf = await this._valid(ref, "form_validate");
              result = result && rf;
            }
          }
        }
        resolve(result);
      });
    },
  },
};
</script>
  <style lang="scss" scoped>
.box {
  width: 100%;
  .title {
    border-left: 3px solid #3280fc;
    padding-left: 5px;
    box-sizing: border-box;
  }
}
.app-container {
  background-color: #fff;
}
</style>
